/**
 * 监听器工具
 */


export class ListenerUtils {

    // 监听列表
    private listeners = new Map<any, Set<Function>>()

    /**
     * 添加监听器
     * @param event     事件
     * @param callback  回调
     */
    addListener(event: any, callback: Function) {
        if (this.listeners.get(event) === undefined) {
            this.listeners.set(event, new Set());
        }
        this.listeners.get(event).add(callback);
        return this.removeListener.bind(this, event, callback);
    }

    /**
     * 移除监听器
     * @param event     事件
     * @param callback  回调
     */
    removeListener(event, callback: Function) {
        if (this.listeners.get(event) === undefined) return;
        this.listeners.get(event).delete(callback);
    }

    /**
     * 触发事件
     * @param event 事件
     * @param args  参数列表
     */
    trigger(event, ...args) {
        if (!(event instanceof Array)) event = [event];
        event.forEach(e => {
            if (this.listeners.get(e) === undefined) return;
            this.listeners.get(e).forEach(f => f.call(this, ...args));
        })
    }
}

export const CommonListener = new ListenerUtils();
